<template>
  <div class="container">
    <!-- 顶部 -->
    <div class="header">
      <!-- 酒店图片 -->
      <van-image class="image" :src="require('@/assets/image/hotel-1.png')">
        <template v-slot:error>加载失败</template>
      </van-image>
    </div>
    <!-- 页面主体 -->
    <div class="content-container">
      <div class="content">
        <!-- 酒店名称 -->
        <van-sticky>
          <h1 class="hotel-name van-hairline--bottom">{{ hotelInfo.name }}</h1>
          <div class="welcome" v-if="member.id">欢迎光临，尊敬的<span class="member">{{ member.familyName }}{{ member.gender == 0 ? '女士' : '先生' }}</span>！</div>
          <div class="welcome" v-if="!member.id">欢迎光临，请先<a href="register">注册</a>或<a href="login">登录</a>！</div>
        </van-sticky>

        <!-- 酒店地址 -->
        <div class="hotel-location-wrapper">
          <van-row class="hotel-location">
            <van-col span="20" class="left">
              <div class="intro">{{ hotelInfo.locationIntro }}</div>
              <div class="address">{{ hotelInfo.locationAddress }}</div>
            </van-col>
            <van-col span="4" class="right">
              <van-icon name="location"/>
              <span>地图</span>
            </van-col>
          </van-row>
        </div>

        <!-- 简单公告 -->
        <div class="simple-notice">
          <van-notice-bar left-icon="volume-o" background="#fff" color="#606161" :scrollable="false">
            <van-swipe vertical class="notice-swipe" :autoplay="3000" :show-indicators="false">
              <van-swipe-item v-for="(notice, i) in noticeList" :key="i">{{ notice.title }}</van-swipe-item>
            </van-swipe>
          </van-notice-bar>
        </div>

        <!-- 会员权益简介 -->
        <div class="vip-rights">
          <span class="label">会员权益</span>
          <ul class="rights">
            <li class="item" v-for="(vipRight, i) in vipRights" :key="i">{{ vipRight }}</li>
            <li class="item">其它</li>
          </ul>
        </div>

        <!-- 房型列表区域 -->
        <div class="room-type-list-wrapper">
          <!-- 选择日期区间组件 -->
          <div class="select-date-wrapper">
            <van-cell-group>
              <van-cell icon="calendar-o" title-class="select-date-title" label-class="select-date-label"
                        :title="selectedDateText" :label="selectedDateDescription"
                        clickable is-link center
                        @click="onSelectDateShow"/>
            </van-cell-group>
          </div>
          <!-- 房型列表 -->
          <div class="room-type-list">
            <van-cell-group :border="false">
              <van-cell class="room-type-info" clickable v-for="(roomType, i) in roomTypeList" :key="i">
                <template #title>
                  <van-row class="base-info" gutter="20">
                    <van-col span="6">
                      <van-image fit="scale-down" radius="5" :src="roomType.image" />
                    </van-col>
                    <van-col span="18">
                      <div class="name">{{ roomType.name }}</div>
                      <div class="params">{{ roomType.size }}m<sup>2</sup> | {{ roomType.bed }}床 | {{ roomType.window }}</div>
                      <div class="tags">
                        <van-tag plain color="#8cc4fc" v-for="(tag, j) in roomType.tags" :key="j">{{ tag }}</van-tag>
                      </div>
                    </van-col>
                  </van-row>
                </template>
                <template #label>
                  <van-row class="price-info" gutter="20">
                    <van-col span="20">
                      <div class="price" :style="{ color: roomType.stock > 0 ? '#e62e2f': '#999'}"><sub class="original">￥{{ roomType.originalPrice }}</sub><sub>￥</sub>{{ roomType.currentPrice }}<sub>起</sub></div>
                      <div class="price-description">
                        <span v-if="roomType.stock == 0" class="no-stock">已全部被预订</span>
                        <span v-else>
                          <span v-if="roomType.isRunningLow" class="low-stock">仅剩 {{roomType.stock}} 间</span>
                          <span v-else class="ample-stock">房间剩余数量充足</span>
                        </span>
                      </div>
                    </van-col>
                    <van-col span="4">
                      <van-button color="#563d91" :disabled="roomType.stock == 0" @click="onBookingClick(roomType.id)">订</van-button>
                    </van-col>
                  </van-row>
                </template>
              </van-cell>
            </van-cell-group>
          </div>
        </div>
        <!-- 底部 -->
        <div class="footer">
          <p>欢迎光临{{ hotelInfo.name }}</p>
          <p>预订热线：{{ hotelInfo.bookingNumber }}，投诉热线：{{ hotelInfo.feedbackNumber }}</p>
          <p>酒店地址：{{ hotelInfo.locationAddress }}</p>
        </div>

        <!--  底部导航栏 -->
        <van-tabbar route v-model="activeTabBarIndex" active-color="#7458b0" inactive-color="#616161">
          <van-tabbar-item icon="todo-list-o" replace to="/">预订</van-tabbar-item>
          <van-tabbar-item icon="orders-o" replace to="/order-list">订单</van-tabbar-item>
          <van-tabbar-item icon="setting-o" replace to="/settings">设置</van-tabbar-item>
          <van-tabbar-item icon="apps-o" replace to="/api-doc">文档</van-tabbar-item>
        </van-tabbar>

        <!-- 弹窗：选择日期区间组件 -->
        <van-calendar title="请选择入住日期与离店日期" :style="{ height: '450px' }"
                      v-model="selectDateCalendarVisible"
                      type="range" color="#563d91" :max-range="31"
                      allow-same-day :show-confirm="false" :min-date="new Date()"
                      :default-date="[checkInDate, checkOutDate]"
                      :formatter="calendarFormatter"
                      @confirm="onSelectDateConfirm" />

      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      hotelInfo: {
        name: '',
        bookingNumber: '',
        feedbackNumber: '',
        locationIntro: '',
        locationAddress: ''
      },
      noticeList: [],
      vipRights: [
        '折扣10%起',
        '免费早餐1份起',
        '积分倍率130%起'
      ],
      selectedDateText: '',
      selectedDateDescription: '',
      selectDateCalendarVisible: false,
      checkInDate: new Date(),
      checkOutDate: new Date(),
      roomTypeList: [],
      member: {
        id: 0,
        familyName: '',
        givenName: '',
        gender: 0
      },
      activeTabBarIndex: 0
    }
  },
  methods: {
    onSelectDateShow() {
      this.selectDateCalendarVisible = true;
    },
    onSelectDateConfirm(value) {
      this.checkInDate = value[0];
      this.checkOutDate = value[1];

      localStorage.setItem('checkInDate', this.checkInDate.getTime());
      localStorage.setItem('checkOutDate', this.checkOutDate.getTime());

      this.updateSelectCalenderComponentText();
      this.selectDateCalendarVisible = false;
    },
    updateSelectCalenderComponentText() {
      let checkInWeekDayText = this.weekDayFormatter(this.checkInDate);
      let checkOutWeekDayText = this.weekDayFormatter(this.checkOutDate);

      let timestamp1 = this.checkInDate.getTime();
      let timestamp2 = this.checkOutDate.getTime();
      let differenceInMilliseconds = Math.abs(timestamp2 - timestamp1);
      let differenceInDays = Math.floor(differenceInMilliseconds / (1000 * 60 * 60 * 24));

      let checkOutDateText = `${checkOutWeekDayText}离店（共${differenceInDays}天）`;
      if (differenceInDays > 7) {
        checkOutDateText = `${differenceInDays}天后离店（${checkOutWeekDayText}）`;
      }

      this.selectedDateText = `${this.checkInDate.getMonth() + 1}月${this.checkInDate.getDate()}日 - ${this.checkOutDate.getMonth() + 1}月${this.checkOutDate.getDate()}日`;
      this.selectedDateDescription = `${checkInWeekDayText}入住 - ${checkOutDateText}`;
    },
    calendarFormatter(day) {
      let now = new Date();
      let nowMonth = now.getMonth();
      let nowDate = now.getDate();
      if (day.date.getMonth() == nowMonth && day.date.getDate() == nowDate) {
        day.topInfo = '今天';
      }
      if (day.type === 'start') {
        day.bottomInfo = '入住';
      } else if (day.type === 'end') {
        day.bottomInfo = '离店';
      }
      return day;
    },
    weekDayFormatter(date) {
      return ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()];
    },
    loadRoomTypeList() {
      let roomTypeList = [
        { id: 1, image: require("@/assets/image/room-1.png"), name: '大床房', size: '20-25', bed: '1张2*1.8米', window: '部分有窗', tags: ['温馨', '智能'], originalPrice: 600, currentPrice: 520, isRunningLow: false, stock: 10 },
        { id: 2, image: require("@/assets/image/room-2.png"), name: '双床房', size: '25-30', bed: '2张1.2*2米', window: '全部有窗', tags: ['舒适', '家庭'], originalPrice: 700, currentPrice: 630, isRunningLow: true, stock: 0 },
        { id: 3, image: require("@/assets/image/room-3.png"), name: '豪华套房', size: '40-50', bed: '1张2.5*2米', window: '全景落地窗', tags: ['奢华', '景观'], originalPrice: 1200, currentPrice: 1000, isRunningLow: false, stock: 3 },
        { id: 4, image: require("@/assets/image/room-4.png"), name: '标准单人间', size: '15-20', bed: '1张1.2*2米', window: '部分有窗', tags: ['简洁', '商务'], originalPrice: 400, currentPrice: 360, isRunningLow: false, stock: 8 },
        { id: 5, image: require("@/assets/image/room-5.png"), name: '亲子主题房', size: '30-35', bed: '1张2*2米+1张1.2*1.8米', window: '全部有窗', tags: ['亲子', '趣味'], originalPrice: 800, currentPrice: 720, isRunningLow: true, stock: 2 },
        { id: 6, image: require("@/assets/image/room-6.png"), name: '情侣浪漫房', size: '18-22', bed: '1张2*1.8米', window: '无窗', tags: ['浪漫', '私密'], originalPrice: 550, currentPrice: 495, isRunningLow: false, stock: 7 },
        { id: 7, image: require("@/assets/image/room-7.png"), name: '行政楼层套房', size: '45-55', bed: '1张2.5*2米', window: '全景落地窗', tags: ['高端', '安静'], originalPrice: 1500, currentPrice: 1300, isRunningLow: false, stock: 4 },
        { id: 8, image: require("@/assets/image/room-8.png"), name: '三人家庭房', size: '30-35', bed: '2张1.5*2米', window: '全部有窗', tags: ['家庭', '宽敞'], originalPrice: 850, currentPrice: 760, isRunningLow: true, stock: 3 },
        { id: 9, image: require("@/assets/image/room-9.png"), name: '四人团体房', size: '40-45', bed: '4张1.2*2米', window: '全部有窗', tags: ['团体', '实惠'], originalPrice: 1000, currentPrice: 900, isRunningLow: false, stock: 6 },
        { id: 10, image: require("@/assets/image/room-10.png"), name: '海景房', size: '35-40', bed: '1张2*2米', window: '全景海景窗', tags: ['美景', '放松'], originalPrice: 1300, currentPrice: 1100, isRunningLow: true, stock: 1 }
      ];
      this.roomTypeList.push(...roomTypeList);
    },
    loadHotelInfo() {
      let hotelInfo = {
        name: '旺豪酒店北京王府井店',
        bookingNumber: '010-12345678',
        feedbackNumber: '010-87654321',
        locationIntro: '距离天安门广场约1.5公里，步行约25分钟',
        locationAddress: '北京市东城区王府井大街9527号'
      };

      this.hotelInfo = hotelInfo;
      localStorage.setItem('hotelInfo', JSON.stringify(hotelInfo));
    },
    loadNoticeList() {
      let noticeList = [
        { id: 1, title: '禁止携带危险品、违禁品入往，感谢您的配合。' },
        { id: 2, title: '请保管好个人财物，退房时检查行李物品。' },
        { id: 3, title: '请爱护酒店设施，如有损坏需照价赔偿。' }
      ];
      this.noticeList.push(...noticeList);
    },
    loadLoginMember() {
      let loginMemberString = localStorage.getItem('loginMember');
      if (loginMemberString) {
        this.member = JSON.parse(loginMemberString);
      }
    },
    onBookingClick(id) {
      this.$router.push({ path: '/booking', query: { roomTypeId: id } });
    }
  },
  mounted() {
    let checkInDateString = localStorage.getItem('checkInDate');
    if (checkInDateString) {
      this.checkInDate = new Date(parseInt(checkInDateString));
      this.checkOutDate = new Date(parseInt(localStorage.getItem('checkOutDate')));
    } else {
      let tomorrow = new Date();
      tomorrow.setDate(tomorrow.getDate() + 1);

      this.checkInDate = new Date();
      this.checkOutDate = tomorrow;
    }

    let hotelInfoString = localStorage.getItem('hotelInfo');
    if (hotelInfoString) {
      this.hotelInfo = JSON.parse(hotelInfoString);
    } else {
      this.loadHotelInfo();
    }

    this.updateSelectCalenderComponentText();
    this.loadNoticeList();
    this.loadRoomTypeList();
    this.loadLoginMember();
  }
}
</script>

<style scoped>
.container { max-width: 400px; }
.van-tabbar { max-width: 400px; }
.van-popup { max-width: 400px; }

.header { position: absolute; top: 0; left: 0; right: 0; z-index: -1; max-width: 400px; }
.header .image { width: 100%; height: 200px; }

.content-container { background: #fff; border-top-left-radius: 12px; border-top-right-radius: 12px; padding-top: 12px; margin-top: 180px; }
.content-container .content { background: #f6f6f6; text-align: left; }

.hotel-name { background: #fff; color: #363636; text-align: center; line-height: 50px; font-size: 16px; font-weight: bold; margin: 0; }
.welcome { background: #7458b0; color: #efefef; text-align: center; line-height: 28px; font-size: 12px; }
.welcome .member { color: #fff; padding: 0 6px; }
.welcome a { color: #fff; padding: 0 6px; text-decoration: underline; }

.hotel-location-wrapper { background: #fff; padding: 10px; }
.hotel-location { background: #f4fcff; padding: 16px 10px; border-radius: 5px; font-size: 12px; }
.hotel-location .left { display: flex; flex-direction: column; gap: 5px; color: #606161; border-right: 1px solid #e1e1e1; }
.hotel-location .right { display: flex; flex-direction: column; gap: 5px; align-items: center; justify-content: center; }
.hotel-location .right .van-icon { font-size: 16px; color: #000; }

.simple-notice { margin-top: 10px; border-radius: 5px; }
.simple-notice .notice-swipe { height: 40px; line-height: 40px; font-size: 12px; padding-left: 6px; }

.vip-rights { margin-top: 10px; padding: 10px; font-size: 10px; background: #fff; border-radius: 5px; display: flex; align-items: center; gap: 12px; }
.vip-rights .label { flex: 0 0 auto; color: #333; }
.vip-rights .rights { flex: 1 1 auto; display: flex; gap: 8px; }
.vip-rights .rights .item { color: #7c6ba2; }

.room-type-list-wrapper { margin-top: 10px; }

.select-date-title { font-size: 14px; }
.select-date-label { font-size: 11px; }
.select-date-wrapper .van-cell__left-icon { margin-right: 10px; font-size: 24px; color: #a0a0a0; }

.room-type-list { padding: 10px 16px; position: relative; margin-top: 6px; }
.room-type-list::before { height: 16px; content: ""; position: absolute; top: 6px; left: 16px; right: 16px; background-color: #fff; border-radius: 8px; }

.room-type-info .base-info, .room-type-info .price-info { display: flex; align-items: center; }
.room-type-info .van-image { width: 80px; height: 80px; }
.room-type-info .van-button { border-radius: 6px; }
.room-type-info .name { font-size: 16px; }
.room-type-info .params { font-size: 12px; color: #858585; }
.room-type-info .tags { display: flex; gap: 5px; }
.room-type-info .van-tag { font-size: 10px; line-height: 18px; padding: 0 6px; }
.room-type-info .price { text-align: right; color: #e62e2f; font-size: 18px; }
.room-type-info .price .original { color: #999; margin-right: 5px; position: relative;  }
.room-type-info .price .original::before { position: absolute; content: ""; left: 2px; right: 0; top: 36%; height: 1px; background: #656565; }
.room-type-info .price sub { vertical-align: baseline; font-size: 0.6em; padding: 0 2px; }
.room-type-info .price-description { text-align: right; font-size: 10px; }
.room-type-info .price-description .no-stock { color: #999; }
.room-type-info .price-description .low-stock { color: #e62e2f; }
.room-type-info .price-description .ample-stock { color: #7c6ba2; }

.footer { margin-top: 10px; padding-bottom: 60px; }
.footer p { margin: 0; text-align: center; font-size: 11px; color: #999; line-height: 20px; }

::v-deep .van-button--disabled { opacity: 0.2 }
</style>
